package node

import (
	"errors"
	log "github.com/sirupsen/logrus"
	"xj.com/oos-naming-service/config"
	"xj.com/oos-naming-service/error_handler"
	"xj.com/oos-naming-service/utils"
)

type NodeService struct {
}

func New() (s *NodeService) {
	s = new(NodeService)
	return s
}

func (s *NodeService) SilenceCheckAll() {
	nodes := config.Config.Data.Nodes
	for _, n := range nodes {
		log.Debug("数据节点健康检查：", n.Ip)
		resp, err := utils.GetRestRequest().Get(n.Ip + "/health/")
		if err != nil {
			log.Warn("数据节点健康检查出错：", err)
			n.OnLine = false
			continue
		}

		statusCode := resp.StatusCode()
		if statusCode >= 400 {
			log.Warn("数据节点健康检查出错，出错原因是响应码大于或等于400.")
			log.Warn(string(resp.Body()))
			n.OnLine = false
			continue
		}

		n.OnLine = true
	}
}

func (s *NodeService) GetHealthyNodes() []config.Node {
	result := make([]config.Node, config.Config.Data.MinNodes)
	nodes := config.Config.Data.Nodes
	for _, n := range nodes {
		if n.OnLine && len(result) < config.Config.Data.MinNodes {
			result = append(result, n)
		}
	}
	if len(result) == 0 {
		error_handler.HttpPanicIfError(errors.New("没有可用的数据节点。"))
	}

	if len(result) < config.Config.Data.MinNodes {
		log.Warn("健康节点数共：", len(result), "个，小于最小节点数：", config.Config.Data.MinNodes)
	}

	return result
}
